/**
 * 区域管理状态管理
 * @author Wu.Liang
 * @date 2025-01-21
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { regionApi, type RegionData, type CreateRegionDTO, type UpdateRegionDTO } from '@/api/region'
import { communityApi, type CommunityData, type CreateCommunityDTO, type UpdateCommunityDTO } from '@/api/community'
import { buildingApi, type BuildingData, type CreateBuildingDTO, type UpdateBuildingDTO } from '@/api/building'
import { householdApi, type HouseholdData, type CreateHouseholdDTO, type UpdateHouseholdDTO } from '@/api/household'

export const useRegionStore = defineStore('region', () => {
  // 区域相关状态
  const regionTreeData = ref<RegionData[]>([])
  const currentRegion = ref<RegionData | null>(null)
  const regionLoading = ref(false)

  // 社区相关状态
  const communityList = ref<CommunityData[]>([])
  const currentCommunity = ref<CommunityData | null>(null)
  const communityLoading = ref(false)

  // 楼栋相关状态
  const buildingList = ref<BuildingData[]>([])
  const currentBuilding = ref<BuildingData | null>(null)
  const buildingLoading = ref(false)

  // 房户相关状态
  const householdList = ref<HouseholdData[]>([])
  const currentHousehold = ref<HouseholdData | null>(null)
  const householdLoading = ref(false)

  // 计算属性
  const regionTreeComputed = computed(() => regionTreeData.value)
  const communityListComputed = computed(() => communityList.value)
  const buildingListComputed = computed(() => buildingList.value)
  const householdListComputed = computed(() => householdList.value)

  // 区域相关方法
  const getRegionTree = async (parentId?: number) => {
    try {
      regionLoading.value = true
      const response = await regionApi.getRegionTree(parentId)
      regionTreeData.value = response.data
      return response.data
    } catch (error) {
      console.error('获取区域树失败:', error)
      throw error
    } finally {
      regionLoading.value = false
    }
  }

  const createRegion = async (regionData: CreateRegionDTO) => {
    try {
      const response = await regionApi.createRegion(regionData)
      await getRegionTree() // 刷新树
      return response
    } catch (error) {
      console.error('创建区域失败:', error)
      throw error
    }
  }

  const updateRegion = async (id: number, regionData: UpdateRegionDTO) => {
    try {
      const response = await regionApi.updateRegion(id, regionData)
      await getRegionTree() // 刷新树
      return response
    } catch (error) {
      console.error('更新区域失败:', error)
      throw error
    }
  }

  const deleteRegion = async (id: number) => {
    try {
      const response = await regionApi.deleteRegion(id)
      await getRegionTree() // 刷新树
      return response
    } catch (error) {
      console.error('删除区域失败:', error)
      throw error
    }
  }

  // 社区相关方法
  const getCommunityList = async (params?: any) => {
    try {
      communityLoading.value = true
      const response = await communityApi.getCommunityList(params)
      communityList.value = response.data
      return response.data
    } catch (error) {
      console.error('获取社区列表失败:', error)
      communityList.value = []
      throw error
    } finally {
      communityLoading.value = false
    }
  }

  const createCommunity = async (communityData: CreateCommunityDTO) => {
    try {
      const response = await communityApi.createCommunity(communityData)
      await getCommunityList() // 刷新列表
      return response
    } catch (error) {
      console.error('创建社区失败:', error)
      throw error
    }
  }

  const updateCommunity = async (id: number, communityData: UpdateCommunityDTO) => {
    try {
      const response = await communityApi.updateCommunity(id, communityData)
      await getCommunityList() // 刷新列表
      return response
    } catch (error) {
      console.error('更新社区失败:', error)
      throw error
    }
  }

  const deleteCommunity = async (id: number) => {
    try {
      const response = await communityApi.deleteCommunity(id)
      await getCommunityList() // 刷新列表
      return response
    } catch (error) {
      console.error('删除社区失败:', error)
      throw error
    }
  }

  // 楼栋相关方法
  const getBuildingList = async (params?: any): Promise<{ records: any[]; total: number; current?: number; size?: number }> => {
    try {
      buildingLoading.value = true
      const response = await buildingApi.getBuildingList(params)
      
      // 检查返回的数据格式
      if (response.data && typeof response.data === 'object') {
        // 如果是分页对象（包含records和total）
        if ((response.data as any).records && Array.isArray((response.data as any).records)) {
          buildingList.value = (response.data as any).records
          return response.data as any // 返回完整的分页对象
        }
        // 如果是数组格式
        else if (Array.isArray(response.data)) {
          buildingList.value = response.data
          return {
            records: response.data,
            total: response.data.length,
            current: params?.pageNum || 1,
            size: params?.pageSize || 10
          }
        }
      }
      
      // 默认返回空分页对象
      buildingList.value = []
      return {
        records: [],
        total: 0,
        current: params?.pageNum || 1,
        size: params?.pageSize || 10
      }
    } catch (error) {
      console.error('获取楼栋列表失败:', error)
      buildingList.value = []
      return {
        records: [],
        total: 0,
        current: params?.pageNum || 1,
        size: params?.pageSize || 10
      }
    } finally {
      buildingLoading.value = false
    }
  }

  const createBuilding = async (buildingData: CreateBuildingDTO) => {
    try {
      const response = await buildingApi.createBuilding(buildingData)
      await getBuildingList() // 刷新列表
      return response
    } catch (error) {
      console.error('创建楼栋失败:', error)
      throw error
    }
  }

  const updateBuilding = async (id: number, buildingData: UpdateBuildingDTO) => {
    try {
      const response = await buildingApi.updateBuilding(id, buildingData)
      await getBuildingList() // 刷新列表
      return response
    } catch (error) {
      console.error('更新楼栋失败:', error)
      throw error
    }
  }

  const deleteBuilding = async (id: number) => {
    try {
      const response = await buildingApi.deleteBuilding(id)
      await getBuildingList() // 刷新列表
      return response
    } catch (error) {
      console.error('删除楼栋失败:', error)
      throw error
    }
  }

  // 房户相关方法
  const getHouseholdList = async (params?: any) => {
    try {
      householdLoading.value = true
      const response = await householdApi.getHouseholdList(params)
      householdList.value = response.data
      return response.data
    } catch (error) {
      console.error('获取房户列表失败:', error)
      throw error
    } finally {
      householdLoading.value = false
    }
  }

  const createHousehold = async (householdData: CreateHouseholdDTO) => {
    try {
      const response = await householdApi.createHousehold(householdData)
      await getHouseholdList() // 刷新列表
      return response
    } catch (error) {
      console.error('创建房户失败:', error)
      throw error
    }
  }

  const updateHousehold = async (id: number, householdData: UpdateHouseholdDTO) => {
    try {
      const response = await householdApi.updateHousehold(id, householdData)
      await getHouseholdList() // 刷新列表
      return response
    } catch (error) {
      console.error('更新房户失败:', error)
      throw error
    }
  }

  const deleteHousehold = async (id: number) => {
    try {
      const response = await householdApi.deleteHousehold(id)
      await getHouseholdList() // 刷新列表
      return response
    } catch (error) {
      console.error('删除房户失败:', error)
      throw error
    }
  }

  // 重置状态
  const resetState = () => {
    regionTreeData.value = []
    currentRegion.value = null
    communityList.value = []
    currentCommunity.value = null
    buildingList.value = []
    currentBuilding.value = null
    householdList.value = []
    currentHousehold.value = null
  }

  return {
    // 状态
    regionTreeData: regionTreeComputed,
    currentRegion,
    regionLoading,
    communityList: communityListComputed,
    currentCommunity,
    communityLoading,
    buildingList: buildingListComputed,
    currentBuilding,
    buildingLoading,
    householdList: householdListComputed,
    currentHousehold,
    householdLoading,

    // 区域方法
    getRegionTree,
    createRegion,
    updateRegion,
    deleteRegion,

    // 社区方法
    getCommunityList,
    createCommunity,
    updateCommunity,
    deleteCommunity,

    // 楼栋方法
    getBuildingList,
    createBuilding,
    updateBuilding,
    deleteBuilding,

    // 房户方法
    getHouseholdList,
    createHousehold,
    updateHousehold,
    deleteHousehold,

    // 工具方法
    resetState
  }
}) 